<?php

namespace interface\v1;

use verify;

class loginAppClass extends index
{

    /**
     * 给个人用户设置默认设置
     */
    private function setDefaultSetting()
    {
        //生成OA小程序销售设置
        if (self::total(array('table' => 'user_setting', 'where' => "stid = '" . self::$stid . "' and type = 'OA通知设置'")) == 0) {
            insert(array(
                'table' => 'user_setting',
                'field' => [
                    'stid'  => self::$stid,
                    'type'  => 'OA通知设置',
                    'value' => json_encode(['message' => 1], 320),
                ],
            ));
        }

        //判断是否有销售过程统计设置
        if (self::total(array('table' => 'user_setting', 'where' => "stid = '" . self::$stid . "' and type = '销售过程统计'")) == 0) {
            insert(array(
                'table' => 'user_setting',
                'field' => [
                    'stid'  => self::$stid,
                    'type'  => '销售过程统计',
                    'value' => json_encode(["board", "follow_client", "sale_funnel", "follow_type", "follow_rank", "visit_rank"], 320),
                ],
            ));
        }
        //判断是否有销售业绩统计设置
        if (self::total(array('table' => 'user_setting', 'where' => "stid = '" . self::$stid . "' and type = '销售业绩统计'")) == 0) {
            insert(array(
                'table' => 'user_setting',
                'field' => [
                    'stid'  => self::$stid,
                    'type'  => '销售业绩统计',
                    'value' => json_encode(["board", "performance_goals", "payment", "contract_money", "kpi_analysis", "losing_analysis", "sign_ranking", "goal_achievement"], 320),
                ],
            ));
        }
        //判断是否有客户分析设置
        if (self::total(array('table' => 'user_setting', 'where' => "stid = '" . self::$stid . "' and type = '客户分析'")) == 0) {
            insert(array(
                'table' => 'user_setting',
                'field' => [
                    'stid'  => self::$stid,
                    'type'  => '客户分析',
                    'value' => json_encode(["geographical", "industry_scale", "status_funnel", "channel_analysis", "customer_add", "customer_ranking", "conversion_rate"], 320),
                ],
            ));
        }
    }

    /**
     * 获取userid
     *
     * @return void
     */
    public function getuserId()
    {
        $source = !empty($this->header['Source']) ? $this->header['Source'] : '';
        $code   = $this->post('code');
        if ($source) {
            $source = strtolower($source);
        } else {
            $source = 'erp';
        }
        $token = static::getSuiteToken($source);
        if (empty($code)) {
            $this->resp['warn'] = '未找到code';
        } elseif (empty($token)) {
            $this->resp['warn'] = '未找到token,请检查参数配置';
        } else {
            $result = (array)static::request([
                'url' => 'https://qyapi.weixin.qq.com/cgi-bin/service/miniprogram/jscode2session?suite_access_token=' . $token . '&js_code=' . $code . '&grant_type=authorization_code&debug=1',
            ], true);
            if (!isset($result['errcode']) || (isset($result['errcode']) && $result['errcode'] != 0)) {
                $this->resp['warn'] = '获取userId失败' . json_encode($result, 320);
            } else {
                $user = query('user', " weChatUserId= '{$result['open_userid']}'");
                if (empty($user['uid'])) {
                    if (para('wechatMiniLoginLimit') == '是') {
                        $this->resp['warn'] = '登录失败，请在后台绑定企业微信ID'.$result['open_userid'];
                    } else {
                        //	写入游客信息
                        $stid   = static::getId();
                        $name   = 'Visitor_' . static::getId();
                        $userNo = 'YKID_' . strtoupper(substr(md5(uniqid()), 0, 14));
                        // 写入用户表
                        self::insert([
                            'table' => 'user',
                            'field' => [
                                'uid'          => self::getNo(),
                                'stid'         => $stid,
                                'userNo'       => $userNo,
                                'role'         => '["visitor"]', // 角色游客
                                'name'         => $name,
                                'userName'     => $name,
                                'password'     => md5s(para('staffPas')),
                                'operator'     => 'system',
                                'state'        => '启用',
                                'weChatUserId' => $result['open_userid'],
                                'time'         => $this->time,
                            ],
                        ]);
                        $orderNo = 'YKXX_' . strtoupper(substr(md5(uniqid()), 0, 14));
                        //	写入员工信息表
                        self::insert([
                            'table' => 'staff',
                            'field' => [
                                'stid'     => $stid,
                                'orderNo'  => $orderNo,
                                'name'     => $name,
                                'state'    => '转正',
                                'workFlow' => '已复核',
                                'ico'      => 'img/websiteImg/replaceHead.jpg',
                                'time'     => $this->time,
                            ],
                        ]);

                        // 返回数据
                        $this->code = 1;
                        $this->setDefaultSetting();
                        $token = md5s($stid);
                        (int)$expireTime = para('expireTime') ?? 2; //登录有效期，单位小时
                        $expireTime = 60 * 60 * $expireTime;
                        $this->rSet($token, $stid, $expireTime); // 设置redis
                        $this->resp['data']['token'] = $token;
                    }
                } else {
                    $logText    = match ($source) {
                        'crm'   => $user['name'] . '登录成功【CRM-小程序】-userId',
                        'erp'   => $user['name'] . '登录成功【ERP-小程序】-userId',
                        default => $user['name'] . '登录成功【OA-小程序】-userId',
                    };
                    $this->code = 1;
                    $this->setDefaultSetting();
                    $token = md5s($user['stid']);
                    (int)$expireTime = para('expireTime') ?? 2; //登录有效期，单位小时
                    $expireTime = 60 * 60 * $expireTime;
                    $this->rSet($token, $user['stid'], $expireTime); // 设置redis
                    // 返回参数
                    unset($result['errcode'], $result['errmsg']);
                    $this->resp['data']          = $result;
                    $this->resp['data']['token'] = $token;
                    $this->logText(["type" => 'my', "text" => $logText], true);
                }
            }
        }
    }


    /**
     * 其他企业的人员访问本企业是产生加密userId
     */
    public function getUid()
    {
        $source = !empty($this->header['Source']) ? $this->header['Source'] : '';
        $code   = $this->post('code');
        if ($source) {
            $source = strtolower($source);
        } else {
            $source = 'erp';
        }
        $token = static::getSuiteToken($source);
        if (empty($code)) {
            $this->resp['warn'] = '未找到code';
        } elseif (empty($token)) {
            $this->resp['warn'] = '未找到token';
        } else {
            $result = static::request([
                'url' => 'https://qyapi.weixin.qq.com/cgi-bin/service/miniprogram/jscode2session?suite_access_token=' . $token . '&js_code=' . $code . '&grant_type=authorization_code&debug=1',
            ], true);
            if ($result['errcode'] != 0) {
                $this->resp['warn'] = '获取userId失败' . json_encode($result, 320);
            } else {
                $this->code                    = 1;
                $this->resp['data']['uid']     = $result['open_userid'];
                $this->resp['data']['isLocal'] = 0;
                if ($result['corpid'] == para('qyWeChatCorpid')) {
                    $this->resp['data']['isLocal'] = 1;
                }
            }
        }
    }


    /**
     * 小程序登录(可通过openId转userId间接登录  https://developer.work.weixin.qq.com/document/path/90202)
     */
    public function weChatLogin()
    {
        $code   = $this->post('code');
        $source = !empty($this->header['Source']) ? $this->header['Source'] : '';
        switch ($source) {
            case 'crm';
                $appid  = para('wxCrmAppid');
                $secret = para('wxCrmAppSecret');
                break;
            case 'erp';
                $appid  = para('wxErpAppid');
                $secret = para('wxErpAppSecret');
                break;
            default;//OA
                $appid  = para('wxOaAppid');
                $secret = para('wxOaAppSecret');
                break;
        }
        $result = json_decode(self::curlGet("https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code"), true);
        if (!isset($result['openid']) || empty($result['openid'])) {
            $this->resp['warn'] = $result['errmsg'];
        } else {
            $openid = $result['openid'];
            $token  = match ($source) {
                'crm'   => wechatToken('crmAccessToken'),
                'erp'   => wechatToken('erpAccessToken'),
                default => wechatToken('oaAccessToken'),
            };
            if (empty($code)) {
                $this->resp['warn'] = '未找到code';
            } elseif (empty($token)) {
                $this->resp['warn'] = '未找到token';
            } else {
                $url    = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_userid?access_token={$token}";
                $result = json_decode(self::curlPost($url, json_encode(['openid' => $openid], 320), build: false), true);
                if ($result['errcode'] != 0) {
                    $this->resp['warn'] = $result['errmsg'];
                } else {
                    $user = query('user', " weChatUserId= '{$result['open_userid']}'");
                    if (empty($user['uid'])) {
                        $this->resp['warn'] = '登录失败，请在后台绑定企业微信ID';
                    } else {
                        $logText    = match ($source) {
                            'crm'   => $user['name'] . '登录成功【CRM-小程序】-微信端',
                            'erp'   => $user['name'] . '登录成功【ERP-小程序】-微信端',
                            default => $user['name'] . '登录成功【OA-小程序】-微信端',
                        };
                        $this->code = 1;
                        $this->setDefaultSetting();
                        $token = md5s($user['stid']);
                        (int)$expireTime = para('expireTime') ?? 2; //登录有效期，单位小时
                        $expireTime = 60 * 60 * $expireTime;
                        $this->rSet($token, $user['stid'], $expireTime); // 设置redis
                        $this->resp['data']['token'] = $token;
                        $this->logText(["type" => 'my', "text" => $logText], true);
                    }
                }
            }
        }
    }

    public function login()
    {
        $token  = $this->header['Auth'];
        $source = $this->header['Source'];
        if (!$token) {
            //走userId登录流程
            $this->resp['warn'] = '未找到token';
        } else {
            $stid = $token == -1 ? self::$stid : $this->rGet($token);
            if (!$stid) {
                $this->resp['warn'] = '登录凭证已过期，请重新登录';
            } else {
                $user = query('user', " stid = '$stid' ");
                if (!$user) {
                    $this->resp['warn'] = '未找到此用户';
                } else {
                    (int)$expireTime = para('expireTime') ?? 2; //登录有效期，单位小时
                    $expireTime = 60 * 60 * $expireTime;
                    $this->rSet($token, $user['stid'], $expireTime); // 设置redis
                    $this->resp['data'] = [
                        'token' => $token,
                    ];
                    $logText            = match ($source) {
                        'crm'        => $user['name'] . '登录成功【CRM-小程序】-token',
                        'erp'        => $user['name'] . '登录成功【ERP-小程序】-token',
                        'pda', 'PDA' => $user['name'] . '登录成功【ERP-PDA】-token',
                        default      => $user['name'] . '登录成功【OA-小程序】-token',
                    };
                    $this->code         = 1;
                    $this->logText(["type" => 'my', "text" => $logText], true);
                }
            }
        }
    }

    /**
     * 账号密码登录
     */
    public function loginPWD()
    {
        $data = [
            'userName' => $this->post['userName'] ?? '',
            'password' => $this->post['password'] ?? '',
            'source'   => $this->post['source'] ?? '',
        ];
        // 注释
        $annotation = [
            'userName' => '用户名或手机号',
            'password' => '密码',
            'source'   => '来源',
            // 'deviceID'   => '设备ID',
        ];
        // 规则
        $rules = [
            'userName' => 'required',
            'password' => 'required|min_len:6,max_len:20',
            'source'   => 'required',
        ];
        // 校验是否符合规则
        $vt     = new verify();
        $result = $vt->setAliases($annotation)->validate($data, $rules)->isOk();
        if ($result === false) {
            $this->resp['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
        } else {
            $source = $data['source'];
            unset($data['source']);
            $user = query('user', " userName = '{$data['userName']}' ");
            if (self::isNull($user['uid']) || verifyPwd($data['password'], $user['password']) !== true) {
                $this->resp['warn'] = '登录失败，账号密码输入错误';
            } else {
                $token = md5s($user['stid']);
                (int)$expireTime = para('expireTime') ?? 2; //登录有效期，单位小时
                $expireTime = 60 * 60 * $expireTime;
                $this->rSet($token, $user['stid'], $expireTime); // 设置redis
                $this->resp['data'] = [
                    'token' => $token,
                ];
                $logText            = match ($source) {
                    'crm'        => $user['name'] . '登录成功【CRM小程序】-token',
                    'erp'        => $user['name'] . '登录成功【ERP小程序】-token',
                    'pda', 'PDA' => $user['name'] . '登录成功【ERP-PDA】-userId',
                    default      => $user['name'] . '登录成功【OA小程序】-token',
                };
                $this->code         = 1;
                $this->logText(["type" => 'my', "text" => $logText], true);
            }
        }
    }


    /**
     * 登录重定向
     * @return void
     */
    public function redirect(): void
    {
        $token = $this->get('token');
        $rk    = $this->get('rk');
        if (empty($token) || empty($rk)) {
            exit('参数错误');
        }
        $uid   = static::$redis->get($rk . $token);
        $table = static::$redis->get($rk . $uid . '_table');
        if (empty($uid)) {
            exit('参数错误，请重试');
        } else {
            $where = " uid = '$uid' ";
            $user  = query($table, $where);
            //登录密码错误次数清零
            update([
                "table" => "user",
                "field" => [
                    'deviceId'   => 'SSO登录',
                    'loginError' => 0,
                ],
                "where" => $where,
            ]);
            $record = query('user_setting', "stid = '" . $user['stid'] . "' and type = '当前使用账套'");
            //添加登录记录
            insert([
                "table" => "log",
                "field" => [
                    "type" => "user",
                    "coid" => $record['value'],
                    "stid" => $user['stid'],
                    "text" => ($user['name'] ?: $user['userName']) . "登录了管理员后台，ip地址：" . getIp(),
                    "time" => date("Y-m-d H:i:s"),
                ],
            ]);
            //创建登录session，返回跳转地址
            $_SESSION['stid']     = $user['stid'];
            $_SESSION['deviceId'] = 'SSO登录';
            header("location:" . root . "control/adIndex.html");
            exit();
        }
    }
}
